<template>
  <div class="charts-one">
    <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
      <a-row justify="space-between">
        <a-col :span="7">
          <a-form-item label="名称" :labelCol="{ span: 2 }" :wrapperCol="{ span: 18, offset: 1 }">
            <a-input v-decorator="['planName', { initialValue: '' }]" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col :span="10">
          <a-form-item label="计划类型" :labelCol="{ span: 4 }" :wrapperCol="{ span: 15, offset: 1 }">
            <a-select v-decorator="['types', { initialValue: '0' }]">
              <a-select-option value="0">
                互动广告
              </a-select-option>
              <a-select-option value="1">
                直投广告
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="7" push="4">
          <a-form-model-item>
            <a-space>
              <a-button @click="resetForm">
                重置
              </a-button>
              <a-button :loading="isLoading" key="submit" type="primary" @click="handleQuery">
                查询
              </a-button>
            </a-space>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form>
    <a-row justify="space-between">
      <a-col :span="8">
        <h3>详情列表</h3>
      </a-col>
      <a-col :span="8" offset="8" push="5">
        <a-button type="primary" icon="plus" @click="handleToPlan">
          新建计划
        </a-button>
        <util-modules @refresh="refreshData" @densityChange="densityChange" />
      </a-col>
    </a-row>
    <a-table
      class="my-table"
      :loading="isLoading"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data-source="data"
      :pagination="pagination"
      @change="handleTableChange"
      :size="activeSize"
    >
      <span slot="planName" slot-scope="_, record">
        <a @click="handlePlanEdit(record.id)">{{ record.planName }}</a>
      </span>
      <span slot="topTime" slot-scope="_, record">
        <a-icon
          type="star"
          style="fontSize: 22px;color:#cdcdcd"
          v-if="[0].includes(record.topTime)"
          @click="handleLike(record.topTime, record.id)"
        />
        <a-icon type="star" style="fontSize: 22px;color:#f4ea2a" theme="filled" v-else @click="handleLike(record.topTime, record.id)" />
      </span>
      <span slot="pic" slot-scope="pic, record">
        <div v-if="['-'].includes((record.materialList && record.materialList.length && record.materialList[0].bannerImg) || '')">
          <a-popover title="">
            <template slot="content">
              <img style="width:200px;height:200px;" @click="handleOpenPre(record)" :src="record.materialList[0].images.top" />
            </template>
            <img style="width:50px;height:50px;" :src="record.materialList[0].images.top" />
          </a-popover>
        </div>
        <div
          v-if="
            record.materialList &&
              record.materialList.length &&
              record.materialList[0].bannerImg &&
              record.materialList[0].bannerImg !== '-'
          "
        >
          <a-popover title="">
            <template v-for="(items, index) in record.materialList">
              <template slot="content">
                <div class="more-img" :key="index" v-if="items.bannerImg !== '-'">
                  <img style="width:100px;height:100px;" @click="handleOpenPre(items)" :src="items.bannerImg" />
                  <span style="text-align:center;">{{ items.id }}</span>
                </div>
              </template>
            </template>
            <img style="width:50px;height:50px;" :src="record.materialList[0].bannerImg" />
          </a-popover>
        </div>
        <div v-if="record.materialList.length === 0 || record.materialList[0] == null">
          <span> - </span>
        </div>
      </span>
      <span slot="planCpm" slot-scope="_, record">
        <span v-if="record.planSortType == 0">{{ `CPM ${record.planCpm / 100}` }}</span>
        <span v-if="record.planSortType == 1">{{ `CPC ${record.planCpm / 100}` }}</span>
      </span>
      <span slot="planStatus" slot-scope="_, record">
        <a-badge v-if="record.planStatus == 0" status="default" text="待开始" />
        <a-badge v-if="record.planStatus == 1" status="processing" text="投放中" />
        <a-badge v-if="record.planStatus == 2" status="error" text="已停止" />
      </span>
      <span slot="land" slot-scope="_, record">
        <a @click="handleCapllyLink(record.planLandUrl)">复制链接</a>
      </span>
      <span slot="action" slot-scope="_, record">
        <a-popconfirm
          v-show="[0, 2].includes(record.planStatus)"
          placement="top"
          ok-text="是"
          cancel-text="否"
          @confirm="handleLaunch(record)"
        >
          <template slot="title">
            <p>确认投放吗</p>
          </template>
          <a>开始投放</a>
        </a-popconfirm>
        <a-popconfirm
          v-show="[1].includes(record.planStatus)"
          placement="top"
          ok-text="是"
          cancel-text="否"
          @confirm="handleLaunch(record)"
        >
          <template slot="title">
            <p>确认停止投放吗?</p>
          </template>
          <a>停止投放</a>
        </a-popconfirm>
        <a-divider type="vertical" />
        <a @click="handleLookData(record)">查看数据</a>
      </span>
    </a-table>
    <a-modal v-model="visible" title="请复制地址" @ok="handleOk">
      <a-textarea v-model="siteLink" :auto-size="{ minRows: 2, maxRows: 6 }" />
    </a-modal>
  </div>
</template>

<script>
import { columns } from './Plan'
import { toRoute, getTableSize } from '../../lib/utils'
import UtilModules from '_c/UtilModules.vue'
import { getAdvertPlanList, postAdvertPlanTop, postAdvertPlanUnTop, postAdvertPlanStart, postAdvertPlanStop } from '@/api/Advertising/api'
export default {
  name: 'Plan',
  components: {
    UtilModules,
  },
  data() {
    return {
      activeSize: '',
      siteLink: '',
      visible: false,
      columns,
      data: [],
      isLoading: false,
      form: this.$form.createForm(this, { name: 'plan' }),
      dateFormat: 'YYYY/MM/DD',
      monthFormat: 'YYYY/MM',
      dateFormatList: ['DD/MM/YYYY', 'DD/MM/YY'],
      pagination: {
        defaultPageSize: 100,
        showSizeChanger: true, // 显示可改变每页数量
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: (total) => `总共  ${total} 条`, // 显示总数
      },
    }
  },
  mounted() {
    this.advertPlanList()
  },
  methods: {
    change(current, size) {
      console.log(current, size)
    },
    /**
     * @func 刷新数据
     */
    refreshData() {
      this.advertPlanList()
    },
    /**
     * @func 表格密度
     */
    densityChange(value) {
      const { tableSize } = this.$store.state
      this.activeSize = getTableSize(value, tableSize)
    },
    /**
     * @func API列表
     */
    async advertPlanList(param) {
      this.isLoading = true
      try {
        const { list, count } = await getAdvertPlanList({ ...param })
        const pager = { ...this.pagination }
        pager.total = count
        this.isLoading = false
        if (list) {
          this.data = list ?? []
        }
        this.pagination = pager
      } catch (err) {
        this.isLoading = false
        this.$msgErr(err.message)
      }
    },
    /**
     * @func API置顶
     */
    async advertPlanTop(id) {
      try {
        await postAdvertPlanTop({ id })
        this.$msgSuc('置顶成功')
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func API取消置顶
     */
    async advertPlanUnTop(id) {
      try {
        await postAdvertPlanUnTop({ id })
        this.$msgSuc('取消置顶成功')
      } catch (err) {
        this.$msgErr(err.message)
      }
    },
    /**
     * @func 开启投放
     */
    async advertPlanStart(record) {
      try {
        await postAdvertPlanStart({ ...record })
        this.$msgSuc('已启动!')
      } catch (err) {
        this.$msgErr(err?.message)
      }
    },

    /**
     * @func 停止投放
     */
    async advertPlanStop(record) {
      try {
        await postAdvertPlanStop({ ...record })
        this.$msgSuc('已停止投放!')
      } catch (err) {
        this.$msgErr(err?.message)
      }
    },
    /**
     * @func 查询数据
     */
    handleQuery(e) {
      e.preventDefault()
      const status = this.planStatus
      this.form.validateFields((err, values) => {
        if (!err) {
          for (let items in values) {
            if (!values[items]) {
              values[items] = ''
            }
          }
          const newArr = { status, ...values }
          this.advertPlanList(newArr)
        }
      })
    },
    /**
     * @func 重置表单
     */
    resetForm() {
      this.advertPlanList()
      this.form.resetFields()
    },
    /**
     * @func 跳转至 新建计划页面
     */
    handleToPlan() {
      toRoute(this, 'plan-create')
    },
    /**
     * @func 表格改变时
     */
    async handleTableChange(pagination, filters) {
      const { planStatus } = filters
      this.planStatus = planStatus
      const pager = { ...this.pagination }
      pager.current = pagination.current
      this.pagination = pager
      const types = this.form.getFieldValue('types')
      this.advertPlanList({ status: planStatus, types, pageNo: pagination.current, pageSize: pagination.pageSize })
    },
    /**
     * @func 复制链接
     */
    handleCapllyLink(planLandUrl) {
      this.siteLink = planLandUrl
      this.visible = true
    },
    /**
     * @func 关闭模态框
     */
    handleOk() {
      this.visible = false
    },
    /**
     * @func 置顶当前项
     */
    handleLike(likeStatus, id) {
      const types = this.form.getFieldValue('types')
      if (likeStatus) {
        this.advertPlanUnTop(id)
        this.advertPlanList({ types })
      } else {
        this.advertPlanTop(id)
        this.advertPlanList({ types })
      }
    },
    /**
     * @func 图片预览
     */
    handleOpenPre(record) {
      /**
       * @desc 如果没有主图，说明是多图
       */
      let images = ['-'].includes(record.bannerImg) ? [record.materialList[0].images.top] : [record.bannerImg]
      if (!images[0]) {
        images = [record.materialList[0].images.top]
      }
      this.$viewerApi({
        images,
      })
    },
    /**
     * @func 开始投放
     */
    handleLaunch(record) {
      if ([0, 2].includes(record.planStatus)) {
        this.advertPlanStart(record)
        this.advertPlanList()
      } else {
        this.advertPlanStop(record)
        this.advertPlanList()
      }
    },
    /**
     * @func 查看数据
     */
    handleLookData(record) {
      const { id, planType, planName } = record
      this.$router.push(`/data?id=${id}&planType=${planType}&planName=${planName}`)
    },
    /**
     * @func 计划详情
     */
    handlePlanEdit(id) {
      toRoute(this, `plan-edit?id=${id}`)
    },
  },
}
</script>
<style lang="scss" scoped>
.my-table {
  margin-top: 20px;
}
.more-img {
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  padding: 20px 0;
  &:last-child {
    border: none;
  }
}
</style>
